package com.azt.provider.impl;

import com.azt.api.dto.BranchCompanyManage;
import com.azt.api.dto.company.CompanyProviderExt;
import com.azt.api.dto.company.CompanySearchParam;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.model.AjaxJson;
import com.azt.model.IDText;
import com.azt.model.Ret;
import com.azt.model.page.Pagination;
import com.azt.model.page.TPagination;
import com.azt.provider.mapper.*;
import com.azt.utils.BeanUtils;
import com.azt.utils.CommonUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {

	@Autowired
	private CompanyMapper companyMapper;

	@Autowired
	private CompanyAssetMapper companyAssetMapper;

	@Autowired
	private CompanyBankMapper companyBankMapper;

	@Autowired
	private CompanyInfoMapper companyInfoMapper;

	@Autowired
	private CompanyApplifieldMapper companyApplifieldMapper;

	@Autowired
	private CompanyCategoryMapper companyCategoryMapper;

	@Autowired
	private UserService userService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private CompanyInfoMapper cim;

	@Autowired
	private MsgUserService msgUserService;

	@Autowired
	private UserPermissionService userPermissionService;
	
	@Autowired
	private FunctionService functionService; 

	@Autowired
	private MsgConfigService msgConfigService;
	
	@Autowired
	private IntegralService integralService;

	@Autowired
	private CompanyExtMapper companyExtMapper;

	@Autowired
	private CoinService coinService;

	@Autowired
	private MemberService memberService;
	@Override
	public Pagination getCompanyPage(int pageno, int pagesize, Map<String, String> searchMap) {
		Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<CompanyVO> companyList = companyMapper.queryCompanysBySQL(searchMap);
		Pagination p = new Pagination(startPage, companyList);
		p.setList(companyList);
		p.setParams(searchMap);
		return p;

	}

	@Override
	public Company showComDetails(String comid) {
		return companyMapper.selectMainCompanyByid(comid);
	}

	@Override
	public void editcompany(Company company) {
		Company com = companyMapper.selectMainCompanyByid(company.getId().toString());
		if (company.getEditType().equals("basic")) {// 内容模块修改
			//company.setIsprovider(company.getIsprovider()==null?0:company.getIsprovider());
			//company.setIspurchaser(company.getIspurchaser()==null?0:company.getIspurchaser());
			company.getCompanyInfo().setId(com.getCompanyInfo().getId());
			companyMapper.updateByPrimaryKeySelective(company);
			companyInfoMapper.updateByPrimaryKeySelective(company.getCompanyInfo());
		} else if (company.getEditType().equals("field")) {// 应用领域模块修改
			companyMapper.deleteCompanyAppBycid(com.getId());
			companyMapper.deleteCompanyCateBucid(com.getId());
			companyCategoryMapper.insertList(company.getCompanyCategorys());
			companyApplifieldMapper.insertList(company.getCompanyApplifields());
		} else {// 银行模块修改
			List<CompanyBank> editBanklist = company.getCompanyBanks();
			for (CompanyBank bank : editBanklist) {
				companyBankMapper.updateByPrimaryKeySelective(bank);
			}
		}
	}

	@Override
	public List findCompanyByQuery(String query, Integer matchCount) {
		Example example = new Example(Company.class);
		example.createCriteria().andEqualTo("auditState", 3).andLike("companyName", "%"+query+"%");
		example.orderBy("id").asc();
		example.selectProperties("id", "companyName");

		PageHelper.startPage(1, matchCount);
		List<Company> companyList = companyMapper.selectByExample(example);

		List<Map> list = new ArrayList<>();
		for (Company company : companyList) {
			Map m = BeanUtils.copyBean2Map(company);
			list.add(m);
		}
		return list;
	}

	public List<Map<String, Object>> queryNeedListBysql(String ind, String ids) {
		return null;

	}
	public List<Integer> initUserListToInteger(List<User> users){
		List<Integer> userIds=new ArrayList<Integer>();
		for (User u:users) {
			userIds.add(u.getId());
		}
		return userIds;
	}
	@Override
	public AjaxJson changeCompanyState(String id, Integer operateId) {
		Company com = companyMapper.selectByPrimaryKey(CommonUtil.safeToInteger(id));
			try {
			userPermissionService.ReviewedUserRole(com.getId());
			List<User> admins=getAdminIdsByCompanyId(CommonUtil.safeToInteger(id));
			boolean fstSend = false;
			if(com.getFirstPass() == 1) {
				//第一次审核通过的时候  保存下属用户到u_msg_enquiry_send中
				if (com.getIsprovider() != null && com.getIsprovider().compareTo(1) == 0) {//只有拥有供应商身份的时候才存
					List<User> users = userMapper.selectByCompanyId(CommonUtil.safeToInteger(id));
					if(CollectionUtil.isNotEmpty(users)){
						for (User user : users) {
							if (userPermissionService.ifProviderRole(user.getId())) {//如果有供应商的角色  才可以报错
								msgUserService.insertByUserAndCompany(user.getId() , CommonUtil.safeToInteger(id));
							}
						}
					}
				}
				//赠送安装币
				coinService.addCompanyCoin("u_reg_coin", com.getId(), null, null, operateId);

				if(CollectionUtil.isNotEmpty(admins)) {
					Integer adminId = admins.get(0).getId();
					if(adminId != null) {
						integralService.addUserRecord(adminId, "company_authentic", null, null, null);    //赠送积分
						CoinRule coinRule = coinService.getEffectiveRule("u_reg_coin");
						IntegralRule scoreRule = integralService.getIngralRuleByCode("company_authentic");
						if(coinRule != null && scoreRule != null) {
							msgConfigService.sendMessage("COMPANY_FSTPASS", Ret.create("coinCount", coinRule.getAmount().intValue()).set("scoreCount", scoreRule.getScore().intValue()), null, false, adminId);
							fstSend = true;
						}
					}
				}
			}
			companyMapper.changeCompanyStateByid(Integer.parseInt(id));
			if(!fstSend) {
				if (admins.size() > 0) {
					msgConfigService.sendMessage("C_REV_PASS", new HashMap<String, String>(), null, initUserListToInteger(admins));
				} else {
					List<User> register = userMapper.selectByCompanyId(CommonUtil.safeToInteger(id));
					msgConfigService.sendMessage("C_REV_PASS", new HashMap<String, String>(), null, initUserListToInteger(register));
				}
			}
			return AjaxJson.success("操作成功");
		} catch (Exception e) {
			return AjaxJson.error("系统繁忙");
		}
	}

	@Override
	public AjaxJson changeSendBackCompanyState(String id, String auditOpinion) {
		try {
			Company company = companyMapper.selectByPrimaryKey(CommonUtil.safeToInteger(id));
			company.setAuditState(2);
			company.setAuditOpinion(auditOpinion);
			companyMapper.updateByPrimaryKeySelective(company);
			Map<String, String> params=new HashMap<String,String>();
			params.put("reason", auditOpinion);
			params.put("registime", CommonUtil.formatDate(company.getUpdatetime(), "yyyy-MM-dd HH:mm:ss"));
			List<User> admins=getAdminIdsByCompanyId(CommonUtil.safeToInteger(id));
			if(admins.size()>0){
				msgConfigService.sendMessage("C_REV_NOTPASS", params, null, initUserListToInteger(admins));
			}else{
				List<User> register=userMapper.selectByCompanyId(CommonUtil.safeToInteger(id));
				msgConfigService.sendMessage("C_REV_NOTPASS", params, null, initUserListToInteger(register));
			}
			return AjaxJson.success("操作成功");
		} catch (Exception e) {
			return AjaxJson.error("系统繁忙");
		}
	}


	@Override
	public void saveOrUpdateCompany(Company company, Integer userId , boolean bo) {
		if (company != null) {
			if (company.getId() == null) {
				companyMapper.insertSelective(company);
			} else {
				companyMapper.updateByPrimaryKey(company);
			}
			CompanyInfo cif = company.getCompanyInfo();

			if (cif != null) {
				if ("".equals(cif.getLogo()))
					cif.setLogo(null);
				cif.setCompanyId(company.getId());
				if (cif.getId() != null) {
					companyInfoMapper.updateByPrimaryKey(cif);
				} else {
					companyInfoMapper.insert(cif);
				}
			}

			if (userId != null) {
				// 保存关联
				User user = new User();
				user.setId(userId);
				user.setCompanyId(company.getId());
				userMapper.updateByPrimaryKeySelective(user);
			}
			if(bo){
                Map<String , String > params = new HashMap<String , String >();
                params.put("company" , company.getCompanyName());
//                msgConfigService.sendMessage("EXAMINE_PERSON" , "NOTICE_EXAMINE" , params);//发送短信通知运营进行审核
				msgConfigService.sendMessage("NOTICE_EXAMINE" , params , null , new ArrayList());//发送短信通知运营进行审核
            }
		}
	}

	@Override
	public Company getCompanyById(Integer id) {
		Company company = new Company();
		company.setId(id);
		return companyMapper.selectByPrimaryKey(company);
	}

	@Override
	public List<Map> getOpenBank(String areaCode, String bankCode) {
		Map param = new HashMap();
		param.put("areaCode", areaCode);
		param.put("bankCode", bankCode);
		return companyBankMapper.findOpenBank(param);
	}

	@Override
	public List<Map> findOpenBankByName(String areaCode, String bankName) {
		Map param = new HashMap();
		param.put("areaCode", areaCode);
		param.put("bankName", bankName);
		return companyBankMapper.findOpenBankByName(param);
	}

	@Override
	public void saveOrUpdateBank(CompanyBank bank , boolean blen , String companyName) {//blen  是否更新company的状态
		if (bank != null) {
			if (bank.getId() == null) {
				bank.setCreatetime(new Date());
				companyBankMapper.insert(bank);
			} else {
				bank.setUpdatetime(new Date());
				companyBankMapper.updateByPrimaryKey(bank);
			}
			if(blen){
				companyMapper.changeCompanyState( Company.AUDIT_STATE_EDIT , bank.getCompanyId() );
				Map<String , String > params = new HashMap<String , String >();
				params.put("company" , companyName);
//				msgConfigService.sendMessage("EXAMINE_PERSON" , "NOTICE_BANK" , params);//发送短信通知运营进行审核
				/**
				 * 屏蔽掉财务审核短信   企业资料的财务信息已经去除  2017-03-20
				 */
//				msgConfigService.sendMessage("NOTICE_BANK" , params , null , new ArrayList());//发送短信通知运营进行审核
			}
		}
	}

	@Override
	public void saveOrUpdateAsset(CompanyAsset asset) {
		if (asset != null) {
			if (asset.getId() == null) {
				asset.setCreatetime(new Date());
				companyAssetMapper.insert(asset);
			} else {
				asset.setUpdatetime(new Date());
				companyAssetMapper.updateByPrimaryKey(asset);
			}
		}
	}

	@Override
	public CompanyBank getComapnyBankById(Integer bankId) {
		return companyBankMapper.selectById(bankId);
	}

	@Override
	public CompanyAsset getAssetById(Integer assetId) {
		return companyAssetMapper.selectByPrimaryKey(assetId);
	}

	@Override
	public Company getCompanyByName(String name) {
		List<Company> companies = companyMapper.selectByName(name);
		return CollectionUtils.isNotEmpty(companies) ? companies.get(0) : null;
	}

	@Override
	public Integer getBankCount(Integer companyId) {
		CompanyBank companyBank = new CompanyBank();
		companyBank.setCompanyId(companyId);
		return companyBankMapper.selectCount(companyBank);
	}

	@Override
	public List<Company> searchCompanyByKeyword(String keyword) {
		Example example = new Example(Company.class);
		example.createCriteria().andLike("companyName", "%" + keyword + "%").andEqualTo("auditState", 3)
				.andEqualTo("removed", 0);
		return companyMapper.selectByExample(example);
	}

	@Override
	public CompanyInfo getCompanyInfoByCompanyId(Integer companyId) {
		return cim.selectByCompanyId(companyId);
	}

	@Override
	public CompanyInfo selectByCompanyIdDetail(int companyId) {
		return cim.selectByCompanyIdDetail(companyId);
	}

	@Override
	public void delBankInfo(Integer bankId) {
		companyBankMapper.deleteByPrimaryKey(bankId);
	}

	@Override
	public void delAsset(Integer assetId) {
		companyAssetMapper.deleteByPrimaryKey(assetId);
	}

	@Override
	public Company getTopParentCompany(int companyId) {
		Company company = companyMapper.selectByPrimaryKey(companyId);
		if(company != null && company.getParentId() != null) {
			return getTopParentCompany(company.getParentId());
		} else {
			return company;
		}
	}

	@Override
	public List<Company> findAllChildCompany(int companyId) {
		//todo 待优化
		List<Company> list = new ArrayList<>();
		Company company = companyMapper.selectByPrimaryKey(companyId);
		if (company != null && company.getIspurchaser().intValue() == 1) {
			addChildCompany(company, list);
		}
		return list;
	}

	@Override
	public boolean isChildCompany(int parentId, int childId) {
		List<Company> children = findAllChildCompany(parentId);
		for (Company company : children) {
			if (company.getId().intValue() == childId) {
				return true;
			}
		}
		return false;
	}

	private void addChildCompany(Company company, List<Company> list) {
		if (company != null) {
			Company _company = new Company();
			_company.setParentId(company.getId());
			_company.setAuditState(Company.AUDIT_STATE_PASS);	//审核通过
			List<Company> children = companyMapper.select(_company);
			for (Company child : children) {
				list.add(child);
				addChildCompany(child, list);
			}
		}
	}

	@Override
	public Pagination searchBranchCompany(int pageNo, int pageSize, Integer companyId, Map<String, String> searchMap) {
		String branchCompany = searchMap.get("so_branchCompany");

		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<BranchCompanyManage> selectBranchCompany = companyMapper.selectBranchCompany(companyId, branchCompany);

		Pagination p = new Pagination(startPage, selectBranchCompany);
		p.setParams(searchMap);
		return p;
	}

	
	@Override
	public List<BranchCompanyManage> selectBranchCompany(Integer companyId, String branchCompany) {
		return companyMapper.selectBranchCompany(companyId, branchCompany);
	}
	
	@Override
	public List<String> getCustommerNamesByIds(List<String> cidlist) {

		StringBuffer sb = new StringBuffer();
		boolean isfirst = true;
		for (String id : cidlist) {
			if (!isfirst) {
				sb.append(",");
			} else {
				isfirst = false;
			}
			sb.append(id);
		}
		return companyMapper.getCustommerNamesByIds(sb.toString());
	}

	@Override
	public List<Company> getBranchCompany(Integer companyId) {
		return companyMapper.getBranchCompany(companyId);
	}

	@Override
	public Map getOrderCompanyTip(int companyId) {
		return companyMapper.getOrderCompanyTip(companyId);
	}

	@Override
	public Company createBranchCompany(Company company, Map<String, Object> parseMap) {
		Company branchCompany = new Company();
		if (company != null) {
			String branchCompanyName = (String) parseMap.get("branchCompanyName");
			String parentCompanyId = (String) parseMap.get("parentCompany");
			Integer RoleType = (Integer) parseMap.get("RoleType");
			branchCompany.setCompanyName(branchCompanyName);
			if(parentCompanyId!=null){
				branchCompany.setParentId(Integer.parseInt(parentCompanyId));
			}else{//二级加三级
				branchCompany.setParentId(company.getId());
			}
			branchCompany.setRegistertime(new Date());
			branchCompany.setIfSetRole(company.getIfSetRole());
			branchCompany.setIspurchaser(0);//默认0
			branchCompany.setIsprovider(0);//默认0
			if (RoleType == 1) {
				branchCompany.setIspurchaser(1);// 默认通过
			}
			if (RoleType == 2) {
				branchCompany.setIsprovider(1);// 默认通过
			}
			branchCompany.setProviderMode(company.getProviderMode());
			//branchCompany.setIfAuthen(0);// 未实名认证
			branchCompany.setAuditState(3);// 审核通过
			branchCompany.setRemoved(0);
			branchCompany.setReviewtime(new Date());
			branchCompany.setIfSelf(0);//更新  创建分公司的时候默认不是集采商城    snowler 2017-04-17

			CompanyInfo companyInfo = this.getCompanyInfoByCompanyId(company.getId());

			CompanyInfo newCompanyInfo = new CompanyInfo();

			try {
				BeanUtils.copyBean2Bean(newCompanyInfo, companyInfo);
				newCompanyInfo.setId(null);
				branchCompany.setCompanyInfo(newCompanyInfo);
				this.saveOrUpdateCompany(branchCompany, null , false);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return branchCompany;
	}

	@Override
	public int saveOrUpdateBranchCompany(Company company, Map<String, Object> parseMap,Integer branchCompanyId) {
		int success=1;
		if(company!=null){
			// 权限数据
			Map<String, String[]> functionMap = (Map<String, String[]>) parseMap.get("parent");
			//其他数据
			String branchCompanyName = (String) parseMap.get("branchCompanyName");
			String parentCompanyId = (String) parseMap.get("parentCompany");
			String mobile = (String) parseMap.get("mobile1");
			Integer RoleType = (Integer) parseMap.get("RoleType");
			String realName = (String) parseMap.get("realName");
			//判断user是否存在
			User  user= userService.getUserByMobile(mobile);
			//编辑
			if(branchCompanyId!=null){
				Company branchcompany = this.getCompanyById(branchCompanyId);
				CompanyInfo companyInfo = this.getCompanyInfoByCompanyId(branchCompanyId);
				branchcompany.setCompanyName(branchCompanyName);//更改公司名字
				if(parentCompanyId!=null){
					branchcompany.setParentId(Integer.parseInt(parentCompanyId));
				}else{//二级加三级
					branchcompany.setParentId(company.getId());
				}
				branchcompany.setCompanyInfo(companyInfo);
				this.saveOrUpdateCompany(branchcompany, null , false);
				//查到role
				Map Parameter = new HashMap();
				Parameter.put("companyId", branchcompany.getId());
				Parameter.put("roleType", RoleType);
				Parameter.put("ifAdmin", 1);
				List<Role> roles = userPermissionService.getRoleByParameter(Parameter);
				List<User> userByAdminRole = userService.getUserByAdminRole(branchcompany.getId(), roles);
				
				if (roles != null && roles.size() == 1) {
					Role role =roles.get(0);
					
					//删除userrole关系
					if (userByAdminRole != null && userByAdminRole.size() == 1) {
						User olduser=userByAdminRole.get(0);
						UserRole olduserRole= userPermissionService.getUserRoleByRoleId(role.getId(), olduser.getId());
						//删除老的userrole关系
						userPermissionService.deleteUserRole(olduserRole);
						
						//先解绑之前的用户（可能更改了号码）
						olduser.setCompanyId(null);
						userService.saveOrUpdate(olduser);
						
						
						if(user==null){//新号码注册的
							//创建新user
							User registerUser = userService.registerNoAuth(mobile, CommonUtil.DEFUALT_USER_PASSWORD, realName,
									branchCompanyId, role.getId(),null);
							//老user变成注册用户
							Role olderRole=userPermissionService.getRoleByCode("register");
							userPermissionService.createUserRole(olderRole, olduser);
							
						}else{//否则可能是自己或已存在的用户（其他人的号码之前已验证了）
							user.setCompanyId(branchCompanyId);
							user.setRealName(realName);
							userService.saveOrUpdate(user);
							userPermissionService.createUserRole(role, user);
						}
						
						functionService.delAuthorityByRoleId(role.getId());
						// 创建分公司权限菜单
						functionService.createBranchAuthority(role.getId(), functionMap);
					}else{
						success=0;
					}
					
				}else{
					success=0;
				}
                				
			}else{//新增
				Company BranchCompany = this.createBranchCompany(company, parseMap);
				// 创建一个默认管理员
				Role role = new Role();
				role.setName(CommonUtil.DEFUALT_USER_ROLENAME);
				role.setCompanyId(BranchCompany.getId());
				role.setRoleType(RoleType);
				role.setIfAdmin(1);
				role.setIfDefault(0);
				role.setRemoved(0);
				userPermissionService.saveRole(role);
				
				//判断user是否存在
				if(user==null){//新号码注册
					//创建新user和userrole关系
					User registerUser = userService.registerNoAuth(mobile, CommonUtil.DEFUALT_USER_PASSWORD, realName,
							BranchCompany.getId(), role.getId(),null); 
				}else{
					user.setRealName(realName);
					user.setCompanyId(BranchCompany.getId());
					userService.saveOrUpdate(user);
					
					//清除老的userrole防止退出公司的注册用户
					//UserRole olduserRole= userPermissionService.getUserRoleByRoleId(roles.get(0).getId(), user.getId());
					UserRole olduserRole=new UserRole();
					olduserRole.setUserId(user.getId());
					//解除老的userrole关系
					userPermissionService.deleteUserRole(olduserRole);
					
					//创建新的userrole
					userPermissionService.createUserRole(role, user);
				}
			
				
				// 创建分公司权限菜单
				functionService.createBranchAuthority(role.getId(), functionMap);
			}
		}else{
			success=2;
		}
		
		return success;
	
	}

	@Override
	public void delBranchCompany(Integer branchCompanyId) {
		Company branchcompany = this.getCompanyById(branchCompanyId);
		//删除分公司数据
		if(branchcompany!=null){
			//查询一级公司
			Company topParentCompany = this.getTopParentCompany(branchCompanyId);
			//解绑公司将一级公司名带入
			if(topParentCompany!=null){
				branchcompany.setCompanyName(topParentCompany.getCompanyName()+"-"+branchcompany.getCompanyName());
			}
			branchcompany.setParentId(null);
			branchcompany.setAuditState(2);//退回修改
			companyMapper.updateByPrimaryKey(branchcompany);
		}
	}


	public List<CompanyBank> findCompanyBankByCid(int companyId, Integer bankType) {
		CompanyBank companyBank = new CompanyBank();
		companyBank.setCompanyId(companyId);
		companyBank.setBankType(bankType);
		return companyBankMapper.select(companyBank);
	}

	@Override
	public CompanyBank getCompanyPayBank(int companyId) {
		CompanyBank rtn = null;
		CompanyBank companyBank = new CompanyBank();
		companyBank.setCompanyId(companyId);
		companyBank.setBankType(2);		//基本户
		Example example = new Example(CompanyBank.class);
		example.createCriteria().andEqualTo(companyBank);
		example.orderBy("ifDefault").desc().orderBy("createtime").desc();
		List<CompanyBank> basicCompanyBankList = companyBankMapper.selectByExample(example);
		if(basicCompanyBankList == null || basicCompanyBankList.size() == 0) {
			//没有基本户，读取结算户
			CompanyBank companyBank2 = new CompanyBank();
			companyBank2.setCompanyId(companyId);
			companyBank2.setBankType(1);		//结算户
			Example example2 = new Example(CompanyBank.class);
			example2.createCriteria().andEqualTo(companyBank2);
			example2.orderBy("ifDefault").desc().orderBy("createtime").desc();
			List<CompanyBank> jiesuanCompanyBankList = companyBankMapper.selectByExample(example2);
			if(jiesuanCompanyBankList != null && jiesuanCompanyBankList.size() > 0) {
				rtn = jiesuanCompanyBankList.get(0);
			}
		} else {
			rtn = basicCompanyBankList.get(0);
		}
		return rtn;
	}

    @Override
    public void changeDefaultBank(Integer companyId, Integer bankId) throws Exception{
		companyBankMapper.changeDefaultBank(companyId , bankId);
    }

	@Override
	public Boolean checkBranchCompanyName(String branchName, Company company,Integer branchCompanyId) {
		/*	
		//2017.4.10更改添加分公司的时候不验证一级公司
		//首先不能和所有的主公司同名
		List<Company> checkcompany = companyMapper.checkCompanyName(branchName);
		if(checkcompany!=null && checkcompany.size()>0){
		if(branchCompanyId!=null){
				if(checkcompany.size()==1 && checkcompany.get(0).getId().equals(branchCompanyId)){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
			
			
		}
		*/
			//验证同公司三级或二级的是否同名
			Integer companyId=null;
			if(company.getParentId()!=null){//当前二级
				companyId=company.getParentId();
			}else{//当前一级
				companyId=company.getId();
			}
			
			List<Company> allBranchCompany=this.allBranchCompany(companyId);
			//所有分公司
			if(allBranchCompany!=null && allBranchCompany.size()>0){
				for(Company com:allBranchCompany){
					if(branchName.equals(com.getCompanyName())){
						//编辑时有重名
						if(branchCompanyId!=null){
							//不是自己为false
							if(!com.getId().equals(branchCompanyId)){
								return false;
							}
						}else{
							return false;
						}
					}
				}
				return true;
			}else{//没有分公司
				return true;
			}
			
	}

	@Override
	public String getBranchCompanyName(Company company) {
		return null;
	}
	
	@Override
	public List<Company> allBranchCompany(Integer companyId){
		Company company  = this.getCompanyById(companyId);
		if(company.getParentId()!=null){
			return  this.getBranchCompany(companyId);
		}else{
			return companyMapper.getAllBranchCompany(companyId);
		}
	}

	@Override
	public Boolean getCentralizePurchaseByCompanyId(Integer companyId) {

		Member cenMember = memberService.getCenMember(companyId);
		if(cenMember!=null){
			return true;
		}else{
			return false;
		}
	}

    @Override
    public void changeLogo(String logo, Integer companyId) throws Exception {
		companyInfoMapper.changeLogo(logo , companyId);
    }


	@Override
	public List<User> getAdminIdsByCompanyId(Integer companyId) {
		return companyMapper.getAdminIdsByCompanyId(companyId);
	}

	@Override
	public List<Map<String, String>> selectExportCompany(String companyIds) {
		return companyMapper.selectExportCompany(companyIds);
	}

	@Override
	public List<Company> getCompanyByPId(Integer companyId) {
		Company c = new Company();
		c.setParentId(companyId);
		return  companyMapper.select(c);
	}

	@Override
	public CompanyExt getCompanyExtById(Integer id) {
		return companyExtMapper.selectByPrimaryKey(id);
	}

	@Override
	public CompanyExt getCompanyExtByCustomerid(Integer customerId) {
		CompanyExt  ext  = new CompanyExt();
		ext.setCompanyId(customerId);
		return companyExtMapper.selectOne(ext);
	}

	@Override
	public void saveCompanyExt(CompanyExt ext) {
		companyExtMapper.insert(ext);
	}

	@Override
	public void updateCompanyExt(CompanyExt ext) {
		companyExtMapper.updateByPrimaryKey(ext);
	}

	@Override
	public Pagination listCompany(Integer pageNo, Integer pageSize, Map params) {
		Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
		List<Company> list = companyMapper.selectByCondition(params);
		List<IDText> texts = Lists.transform(list, new Function<Company, IDText>() {
			@Override
			public IDText apply(Company company) {
				return new IDText(company.getId().toString(), company.getCompanyName());
			}
		});
		Pagination p = new Pagination(startPage, texts);
		p.setList(texts);
		return p;
	}

	@Override
	public void delCompany(Company company) {
		String newName="(已删除)"+company.getCompanyName();
		company.setCompanyName(newName);
		company.setRemoved(1);
		companyMapper.updateByPrimaryKeySelective(company);
		//查询公司下所有用户
		List<User> users = userService.getUsersBYCompanyId(company.getId());
		if(users!=null && users.size()>0){
			for(User user : users){
				userService.unbindUserFromCompany(user.getId().toString());
			}
		}
	}
	@Override
	public TPagination<CompanyProviderExt> getSearchProvider(CompanySearchParam param) {
		Page<Object> startPage = PageHelper.startPage(param.getPageNo(),param.getPageSize());
		List<CompanyProviderExt> extList = companyExtMapper.getCompanyProvider(param);
		TPagination p = new TPagination(startPage, extList);
		return p;
	}


}
